package com.jic.market.impl.overlay;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.utils.IDUtils;
import com.jic.market.common.constant.CouponConstant;
import com.jic.market.entity.PromotionEntity;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.entity.overlay.OverlayBaseInfo;
import com.jic.market.entity.overlay.OverlayGroupInfo;
import com.jic.market.enums.PromotionTypeEnum;
import com.jic.market.mapper.PromotionEntityMapper;
import com.jic.market.mapper.overlay.OverlayBaseInfoMapper;
import com.jic.market.mapper.overlay.OverlayGroupInfoMapper;
import com.jic.market.mapper.overlay.OverlayPromotionInfoMapper;
import com.jic.market.mapper.overlay.OverlayPromotionRuleMapper;
import com.jic.market.request.manager.overlay.*;
import com.jic.market.response.manager.overlay.OverlayGroupQueryResponse;
import com.jic.market.response.manager.overlay.OverlayInfoQueryResponse;
import com.jic.market.response.manager.overlay.OverlayPromotionResponse;
import com.jic.market.response.manager.overlay.QueryPagePromotionResponse;
import com.jic.market.service.base.BaseActivityService;
import com.jic.market.service.overlay.OverlayBaseInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 叠加规则信息表
 *
 * @author : seven
 * @version : v1.0.0
 * @email : 774329481@qq.com
 * @since : 2020-03-20 04:41:52
 */
@Service
public class OverlayBaseInfoServiceImpl implements OverlayBaseInfoService {

    @Autowired
    private OverlayBaseInfoMapper overlayBaseInfoMapper;
    @Autowired
    OverlayPromotionRuleMapper overlayPromotionRuleMapper;
    @Autowired
    OverlayGroupInfoMapper overlayGroupInfoMapper;
    @Autowired
    OverlayPromotionInfoMapper overlayPromotionInfoMapper;
    @Autowired
    BaseActivityService baseActivityService;
    @Autowired
    PromotionEntityMapper promotionEntityMapper;

    public PageResult<OverlayBaseInfo> queryPage(OverlayBaseInfo overlayBaseInfo, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<OverlayBaseInfo> list = overlayBaseInfoMapper.queryPage(startIndex, pageQuery.getLimit(), overlayBaseInfo);
        long count = overlayBaseInfoMapper.queryPageCount(overlayBaseInfo);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public RestResult<PageResult<QueryPagePromotionResponse>> queryPagePromotion(QueryPagePromotionRequest request) {
        AdminOperate adminOperate = request.getAdminOperate();
        if(PromotionTypeEnum.SINGLELY.getCode().equals(request.getPromType())
            || PromotionTypeEnum.FULL.getCode().equals(request.getPromType())
            || PromotionTypeEnum.GIFT.getCode().equals(request.getPromType())
            || PromotionTypeEnum.COMPLEX.getCode().equals(request.getPromType())
            || PromotionTypeEnum.XOFFER.getCode().equals(request.getPromType())
            || PromotionTypeEnum.increase.getCode().equals(request.getPromType())
            || PromotionTypeEnum.XOFFER.getCode().equals(request.getPromType())
            || PromotionTypeEnum.SINGLE.getCode().equals(request.getPromType())
            || PromotionTypeEnum.LOTTERY.getCode().equals(request.getPromType())
        ){
            //计算下标
            int startIndex = (request.getStart() - 1) * request.getLimit();
            PromotionEntity promotionEntity = new PromotionEntity();
            promotionEntity.setPromName(request.getPromName());
            if(!StringUtils.isEmpty(request.getPromotionId())){
                promotionEntity.setId(Long.valueOf(request.getPromotionId()));
            }
            promotionEntity.setPromType(request.getPromType());
            if(null != adminOperate){
                promotionEntity.setDeptId(adminOperate.getDeptId());
            }
            List<PromotionEntity> list = promotionEntityMapper.queryPage(startIndex, request.getLimit(), promotionEntity);
            int count = promotionEntityMapper.countOfPage(promotionEntity);
            List<QueryPagePromotionResponse> queryPagePromotionResponseList = buildQueryPagePromotionResponse(list);

            PageResult<QueryPagePromotionResponse> pageResult = new PageResult<>();
            pageResult.setRows(queryPagePromotionResponseList);
            pageResult.setTotal(count);
            return RestResult.success(pageResult);
        }else {
            BaseActivity baseActivity = new BaseActivity();
            baseActivity.setPromName(request.getPromName());
            baseActivity.setPromType(request.getPromType().toString());
            baseActivity.setPromotionId(request.getPromotionId());
            if(null != adminOperate){
                baseActivity.setDeptId(adminOperate.getDeptId());
            }
            PageResult<BaseActivity> pageResult = baseActivityService.queryPage(baseActivity, request);
            List<QueryPagePromotionResponse> queryPagePromotionResponseList = new ArrayList<>();
            if(null != pageResult && null != pageResult.getRows()){
                for(BaseActivity activity : pageResult.getRows()){
                    QueryPagePromotionResponse queryPagePromotionResponse = new QueryPagePromotionResponse();
                    queryPagePromotionResponse.setPromName(activity.getPromName());
                    queryPagePromotionResponse.setPromType(activity.getPromType());
                    queryPagePromotionResponse.setPromotionId(activity.getPromotionId());
                    queryPagePromotionResponse.setStartTime(activity.getStartTime());
                    queryPagePromotionResponse.setEndTime(activity.getEndTime());
                    queryPagePromotionResponseList.add(queryPagePromotionResponse);
                }
            }
            PageResult<QueryPagePromotionResponse> responsePageResult = new PageResult<>();
            responsePageResult.setRows(queryPagePromotionResponseList);
            responsePageResult.setTotal(pageResult.getTotal());
            return RestResult.success(responsePageResult);
        }

    }

    @Override
    public RestResult<Boolean> checkPromType(OverlayPromotionInfoCheckRequest request) {
        if(null == request.getTargetList() || request.getTargetList().isEmpty()){
            return RestResult.success(Boolean.TRUE);
        }
        request.getTargetList().add(request.getSource());
        return checkPromType(request.getTargetList());
    }

    private List<QueryPagePromotionResponse> buildQueryPagePromotionResponse(List<PromotionEntity> list) {
        if(null != list){
            List<QueryPagePromotionResponse> queryPagePromotionResponseList = new ArrayList<>();
            for(PromotionEntity promotionEntity : list){
                QueryPagePromotionResponse queryPagePromotionResponse = new QueryPagePromotionResponse();
                queryPagePromotionResponse.setPromotionId(promotionEntity.getId().toString());
                queryPagePromotionResponse.setPromName(promotionEntity.getPromName());
                queryPagePromotionResponse.setPromType(promotionEntity.getPromType().toString());
                queryPagePromotionResponse.setStartTime(promotionEntity.getStartTime());
                queryPagePromotionResponse.setEndTime(promotionEntity.getEndTime());
                queryPagePromotionResponseList.add(queryPagePromotionResponse);
            }
            return queryPagePromotionResponseList;
        }
        return null;
    }

    @Override
    public RestResult<String> addOverlayGroup(OverlayAddRuleGroupRequest overlayAddRuleGroupRequest) {
        if (CollectionUtils.isEmpty(overlayAddRuleGroupRequest.getOverlayPromotionInfoList())) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "活动列表不能为空");
        }
        if (overlayAddRuleGroupRequest.getOverlayPromotionInfoList().size() < CouponConstant.Orerlay.PROMOTION_NUM_MIN_LIMIT) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "选择的活动数过少");
        }
        RestResult checkResult = checkPromType(overlayAddRuleGroupRequest.getOverlayPromotionInfoList());
        if (!RestResult.checkIsSuccess(checkResult)) {
            return checkResult;
        }

        Integer overlayInt = getOverlayType(overlayAddRuleGroupRequest.getOverlayType());
        Integer promotionNum = overlayAddRuleGroupRequest.getOverlayPromotionInfoList().size();
        if (overlayInt == null) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "叠加类型参数不对");
        }
        // 预先传入一个数据结构存放递归结果
        List<List> resultList = new ArrayList<>();
        // TODO result是辅助查询的索引index数组 设置10 如果出现大于10个的叠加需要加大辅助查询数组长度
        int[] indexResult = new int[10];
        List<List> groupList = getGroupList(getPromotionArray(overlayAddRuleGroupRequest.getOverlayPromotionInfoList()),
                0,
                indexResult,
                overlayInt,
                overlayInt,
                promotionNum,
                resultList
        );
        if (CollectionUtils.isEmpty(groupList)) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "生成的叠加规则集合为空");
        }
        String overlayId = saveDataReturnOverlayId(groupList, overlayAddRuleGroupRequest);
        return RestResult.success(overlayId);
    }

    @Override
    public RestResult<Boolean> closeOverlay(OverlayBaseRequest overlayBaseRequest) {
        long flag = overlayBaseInfoMapper.updateStatus(overlayBaseRequest.getOverlayId(), CouponConstant.Orerlay.Status.CLOSE);
        if (flag < 0) {
            return RestResult.error(CouponConstant.Exception.ERROR_CODE, "没有更新成功，请重试");
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteOverlay(OverlayBaseRequest overlayBaseRequest) {
        overlayBaseInfoMapper.delete(overlayBaseRequest.getOverlayId());
        overlayGroupInfoMapper.delete(overlayBaseRequest.getOverlayId());
        overlayPromotionInfoMapper.delete(overlayBaseRequest.getOverlayId());
        return RestResult.success(true);
    }

    @Override
    public RestResult<PageResult<OverlayInfoQueryResponse>> queryOverlayInfo(OverlayInfoQueryRequest overlayInfoQueryRequest) {
        OverlayBaseInfo overlayBaseInfo = new OverlayBaseInfo();
        BeanUtils.copyProperties(overlayInfoQueryRequest, overlayBaseInfo);
        AdminOperate adminOperate = overlayInfoQueryRequest.getAdminOperate();
        if(null != adminOperate){
            overlayBaseInfo.setDeptId(adminOperate.getDeptId());
            overlayBaseInfo.setDeptType(adminOperate.getDeptType().getCode());
        }
        Page pageQuery = new Page();
        pageQuery.setStart(overlayInfoQueryRequest.getStart());
        pageQuery.setLimit(overlayInfoQueryRequest.getLimit());

        PageResult<OverlayBaseInfo> pageResult = queryPage(overlayBaseInfo, pageQuery);

        PageResult resultPage = new PageResult();
        resultPage.setTotal(pageResult.getTotal());

        if (CollectionUtils.isEmpty(pageResult.getRows())) {
            resultPage.setRows(new ArrayList());
            return RestResult.success(resultPage);
        }

        List<OverlayInfoQueryResponse> responseList = new ArrayList<>();
        pageResult.getRows().stream().forEach(temp -> {
            OverlayInfoQueryResponse response = new OverlayInfoQueryResponse();
            BeanUtils.copyProperties(temp, response);
            responseList.add(response);
        });
        resultPage.setRows(responseList);
        return RestResult.success(resultPage);
    }

    @Override
    public RestResult<OverlayGroupQueryResponse> queryOverlayGroupInfo(OverlayGroupInfoQueryRequest overlayGroupInfoQueryRequest) {
        OverlayBaseInfo overlayBaseInfo = overlayBaseInfoMapper.queryByOverlayId(overlayGroupInfoQueryRequest.getOverlayId());
        OverlayGroupQueryResponse response = new OverlayGroupQueryResponse();
        response.setOverlayId(overlayBaseInfo.getOverlayId());
        response.setOverlayName(overlayBaseInfo.getOverlayName());
        // TODO 请求体和数据库实体名字一样导致import太长,后期可以优化
        List<com.jic.market.response.manager.overlay.OverlayGroupInfo> groupInfoList = getGroupInfoList(overlayGroupInfoQueryRequest);
        response.setGroupInfoList(groupInfoList);
        return RestResult.success(response);
    }

    @Override
    public RestResult<Boolean> setOverlayGroup(OverlayGroupUpdateRequet overlayGroupUpdateRequet) {
        long flag = overlayGroupInfoMapper.updateFullAmountReduceFlag(overlayGroupUpdateRequet.getFullAmountReduceFlag(),
                overlayGroupUpdateRequet.getOverlayId(), overlayGroupUpdateRequet.getOverlayGroupId());
        if (flag > 0) {
            return RestResult.success(true);
        }
        return RestResult.error(CouponConstant.Exception.ERROR_CODE, "更新失败,请重试!");
    }

    @Override
    public RestResult<Boolean> addOverlayGroupPromotionInfo(OverlayGroupAddPromotionRequest overlayGroupAddPromotionRequest) {
        List<com.jic.market.entity.overlay.OverlayPromotionInfo> promotionInfoList = overlayPromotionInfoMapper.queryOverlayPromotionByOverlayGroupId(overlayGroupAddPromotionRequest.getOverlayId(),
                overlayGroupAddPromotionRequest.getOverlayGroupId());
        List<OverlayPromotionInfo> overlayPromotionInfoList = overlayGroupAddPromotionRequest.getOverlayPromotionInfoList();

        AdminOperate adminOperate = overlayGroupAddPromotionRequest.getAdminOperate();
        if (!CollectionUtils.isEmpty(promotionInfoList)) {
            promotionInfoList.stream().forEach(temp -> {
                OverlayPromotionInfo overlayPromotionInfo = new OverlayPromotionInfo();
                BeanUtils.copyProperties(temp, overlayPromotionInfo);
                overlayPromotionInfoList.add(overlayPromotionInfo);
            });
        }

        RestResult restResult = checkPromType(overlayPromotionInfoList);
        if (!RestResult.checkIsSuccess(restResult)) {
            return restResult;
        }

        if (!CollectionUtils.isEmpty(overlayPromotionInfoList)) {
            overlayPromotionInfoList.stream().forEach(temp -> {
                // 数据库已经存在数据，做更新操作
                com.jic.market.entity.overlay.OverlayPromotionInfo overlayPromotionInfoQ = new com.jic.market.entity.overlay.OverlayPromotionInfo();
                overlayPromotionInfoQ.setOverlayGroupId(overlayGroupAddPromotionRequest.getOverlayGroupId());
                overlayPromotionInfoQ.setPromotionId(temp.getPromotionId());
                List<com.jic.market.entity.overlay.OverlayPromotionInfo> overlayPromotionInfoQList = overlayPromotionInfoMapper.query(overlayPromotionInfoQ);
                //加过了暂时不加了
                if(null != overlayPromotionInfoQList && !overlayPromotionInfoQList.isEmpty()){
                }else {
                    com.jic.market.entity.overlay.OverlayPromotionInfo overlayPromotionInfo = new com.jic.market.entity.overlay.OverlayPromotionInfo();
                    overlayPromotionInfo.setPromotionId(temp.getPromotionId());
                    overlayPromotionInfo.setOverlayGroupId(overlayGroupAddPromotionRequest.getOverlayGroupId());
                    overlayPromotionInfo.setOverlayId(overlayGroupAddPromotionRequest.getOverlayId());
                    overlayPromotionInfo.setPromType(temp.getPromType());
                    overlayPromotionInfo.setDeleteFlag(false);
                    if(null != adminOperate){
                        overlayPromotionInfo.setDeptId(adminOperate.getDeptId());
                        overlayPromotionInfo.setDeptType(adminOperate.getDeptType().getCode());
                    }
                    overlayPromotionInfoMapper.insert(overlayPromotionInfo);
                }
            });
        }
        return RestResult.success(true);
    }

    @Override
    public RestResult<Boolean> deleteOverlayGroupPromotionInfo(OverlayGroupDeletePromotionRequest request) {
        long flag = overlayPromotionInfoMapper.deleteOverlayPromotionInfo(request.getOverlayId(),
                request.getOverlayGroupId(),
                request.getOverlayPromotionInfo().getPromotionId(),
                request.getOverlayPromotionInfo().getPromType());
        if (flag > 0) {
            return RestResult.success(true);
        }
        return RestResult.error(CouponConstant.Exception.ERROR_CODE,"删除失败,请重试!");
    }


    private List<com.jic.market.response.manager.overlay.OverlayGroupInfo> getGroupInfoList(OverlayGroupInfoQueryRequest overlayGroupInfoQueryRequest) {
        List<com.jic.market.response.manager.overlay.OverlayGroupInfo> overlayGroupInfos = new ArrayList<>();

        List<OverlayGroupInfo> groupInfoList = overlayGroupInfoMapper.queryGroupList(overlayGroupInfoQueryRequest.getOverlayId());
        if (CollectionUtils.isEmpty(groupInfoList)) {
            return overlayGroupInfos;
        }

        groupInfoList.stream().forEach(temp -> {
            com.jic.market.response.manager.overlay.OverlayGroupInfo overlayGroupInfo = new com.jic.market.response.manager.overlay.OverlayGroupInfo();
            overlayGroupInfo.setOverlayGroupId(temp.getOverlayGroupId());
            overlayGroupInfo.setFullAmountReduceFlag(temp.getFullAmountReduceFlag());
            List<OverlayPromotionResponse> promotionInfoList = getPromotionResponse(overlayGroupInfoQueryRequest.getOverlayId(),
                    temp.getOverlayGroupId());
            overlayGroupInfo.setPromotionInfoList(promotionInfoList);
            overlayGroupInfos.add(overlayGroupInfo);
        });
        return overlayGroupInfos;
    }

    private List<OverlayPromotionResponse> getPromotionResponse(String overlayId, String overlayGroupId) {
        List<OverlayPromotionResponse> responseList = new ArrayList<>();
        List<com.jic.market.entity.overlay.OverlayPromotionInfo> promotionInfoList = overlayPromotionInfoMapper.queryOverlayPromotionByOverlayGroupId(overlayId, overlayGroupId);
        if (CollectionUtils.isEmpty(promotionInfoList)) {
            return responseList;
        }
        promotionInfoList.stream().forEach(temp -> {
            OverlayPromotionResponse response = new OverlayPromotionResponse();
            response.setId(Long.toString(temp.getId()));
            response.setPromotionId(temp.getPromotionId());
            response.setPromType(temp.getPromType());
            // TODO 不在baseAcitivity和Promotion表的需要再加逻辑单独加
            if (checkActivityTableSource(temp.getPromType())) {
                BaseActivity baseActivity = getBaseActivity(temp.getPromotionId(), temp.getPromType());
                if (baseActivity != null) {
                    response.setEndTime(baseActivity.getEndTime());
                    response.setStartTime(baseActivity.getStartTime());
                    response.setPromName(baseActivity.getPromName());
                }
            } else if (checkPromotionTableSource(temp.getPromType())) {
                PromotionEntity promotionEntity = getPromotionEntity(temp.getPromotionId(), temp.getPromType());
                if (promotionEntity != null) {
                    response.setEndTime(promotionEntity.getEndTime());
                    response.setStartTime(promotionEntity.getStartTime());
                    response.setPromName(promotionEntity.getPromName());
                }
            }
            responseList.add(response);
        });
        return responseList;
    }

    private PromotionEntity getPromotionEntity(String promotionId, String promType) {
        PromotionEntity promotionEntity = promotionEntityMapper.queryById(Long.parseLong(promotionId));
        return promotionEntity;
    }

    private boolean checkPromotionTableSource(String promType) {
        return true;
    }

    // TODO 查询活动具体信息 没有加上的自己加逻辑
    private boolean checkActivityTableSource(String promType) {
        if (org.apache.commons.lang3.StringUtils.equals(promType, PromotionTypeEnum.Coupon.getCode().toString()) ||
                org.apache.commons.lang3.StringUtils.equals(promType, PromotionTypeEnum.FULL_NUM.getCode().toString()) ||
                org.apache.commons.lang3.StringUtils.equals(promType, PromotionTypeEnum.SECKILL.getCode().toString()) ||
                org.apache.commons.lang3.StringUtils.equals(promType, PromotionTypeEnum.RED.getCode().toString())) {
            return true;
        }
        return false;
    }

    private BaseActivity getBaseActivity(String promotionId, String promType) {
        BaseActivity baseActivity = baseActivityService.queryByPromotionIdAndPromType(promotionId, promType);
        return baseActivity;
    }

    private String saveDataReturnOverlayId(List<List> groupList, OverlayAddRuleGroupRequest overlayAddRuleGroupRequest) {
        String overlayId = saveOverlayBaseInfo(overlayAddRuleGroupRequest);

        groupList.stream().forEach(temp -> {
            String overlayGroupId = saveOverlayGroupInfo(overlayId, overlayAddRuleGroupRequest.getAdminOperate());
            saveOverlayGroupPromotionInfo(overlayId, overlayGroupId, temp, overlayAddRuleGroupRequest);
        });
        return overlayId;
    }

    private void saveOverlayGroupPromotionInfo(String overlayId, String overlayGroupId, List<String> promotionIdList,
                                               OverlayAddRuleGroupRequest overlayAddRuleGroupRequest) {
        promotionIdList.stream().forEach(promotionId -> {
            com.jic.market.entity.overlay.OverlayPromotionInfo overlayPromotionInfo = new com.jic.market.entity.overlay.OverlayPromotionInfo();
            overlayPromotionInfo.setDeleteFlag(false);
            overlayPromotionInfo.setOverlayGroupId(overlayGroupId);
            overlayPromotionInfo.setOverlayId(overlayId);
            overlayPromotionInfo.setPromotionId(promotionId);
            String promType = getPromTypeByPromotionId(overlayAddRuleGroupRequest, promotionId);
            overlayPromotionInfo.setPromType(promType);
            AdminOperate adminOperate = overlayAddRuleGroupRequest.getAdminOperate();
            if(null != adminOperate){
                overlayPromotionInfo.setDeptId(adminOperate.getDeptId());
                overlayPromotionInfo.setDeptType(adminOperate.getDeptType().getCode());
            }
            overlayPromotionInfoMapper.insert(overlayPromotionInfo);
        });
    }

    private String getPromTypeByPromotionId(OverlayAddRuleGroupRequest overlayAddRuleGroupRequest, String promotionId) {
        OverlayPromotionInfo promotion = overlayAddRuleGroupRequest.getOverlayPromotionInfoList()
                .stream()
                .filter(promotionInfo -> promotionInfo.getPromotionId().equals(promotionId))
                .findFirst()
                .orElse(null);
        if (promotion == null) {
            return "";
        }
        return promotion.getPromType();
    }

    private String saveOverlayGroupInfo(String overlayId, AdminOperate adminOperate) {
        OverlayGroupInfo overlayGroupInfo = new OverlayGroupInfo();
        overlayGroupInfo.setOverlayId(overlayId);
        overlayGroupInfo.setOverlayGroupId(IDUtils.GenerateBillNo());
        overlayGroupInfo.setDeleteFlag(false);
        overlayGroupInfo.setFullAmountReduceFlag(CouponConstant.Orerlay.FullAmountReduceFlag.reduceNo);
        if(null != adminOperate){
            overlayGroupInfo.setDeptId(adminOperate.getDeptId());
            overlayGroupInfo.setDeptType(adminOperate.getDeptType().getCode());
        }
        overlayGroupInfoMapper.insert(overlayGroupInfo);
        return overlayGroupInfo.getOverlayGroupId();
    }

    private String saveOverlayBaseInfo(OverlayAddRuleGroupRequest overlayAddRuleGroupRequest) {
        OverlayBaseInfo baseInfo = new OverlayBaseInfo();
        baseInfo.setOverlayId(IDUtils.GenerateBillNo());
        baseInfo.setDeleteFlag(false);
        baseInfo.setOverlayName(overlayAddRuleGroupRequest.getOverlayName());
        baseInfo.setStatus(CouponConstant.Orerlay.Status.OPEN);
        AdminOperate adminOperate = overlayAddRuleGroupRequest.getAdminOperate();
        if(null != adminOperate){
            baseInfo.setDeptId(adminOperate.getDeptId());
            baseInfo.setDeptType(adminOperate.getDeptType().getCode());
            baseInfo.setCreator(adminOperate.getOperator());;
            baseInfo.setCreatorName(adminOperate.getOperateName());
        }
        overlayBaseInfoMapper.insert(baseInfo);
        return baseInfo.getOverlayId();
    }


    public RestResult<Boolean> checkPromType(String source , List<String> targets) {
        List<String> promTypeTargetList = overlayPromotionRuleMapper.queryPromTypeTargetBySourcePromTypeAndPromTypeTargets(source, targets);
        if(null == promTypeTargetList || promTypeTargetList.isEmpty()){
            return RestResult.success(Boolean.TRUE);
        }
        return RestResult.error(CouponConstant.Exception.ERROR_CODE,
                PromotionTypeEnum.getByCode(Integer.parseInt(source)).getMessage() + "类型与" + PromotionTypeEnum.getByCode(Integer.parseInt(promTypeTargetList.get(0))).getMessage() + "类型的活动不能叠加");
    }
    public RestResult<Boolean> checkPromType(List<OverlayPromotionInfo> overlayPromotionInfoList) {
        List<OverlayPromotionInfo> promotionInfoList = overlayPromotionInfoList;
        List<String> promTypeList = promotionInfoList.stream().map(OverlayPromotionInfo::getPromType).collect(Collectors.toList());
        for(String promTypeSource : promTypeList) {
            List<String> promTypeTargetList = new ArrayList<>(promTypeList);
            promTypeTargetList.remove(promTypeSource);

            RestResult<Boolean> restResult = checkPromType(promTypeSource, promTypeTargetList);
            if(null == restResult.getData()) {
                return restResult;
            }
        }
        return RestResult.success(Boolean.TRUE);
    }
//    public RestResult<Boolean> checkPromType(List<OverlayPromotionInfo> overlayPromotionInfoList) {
//        List<OverlayPromotionInfo> promotionInfoList = overlayPromotionInfoList;
//        List<String> promTypeList = promotionInfoList.stream().map(OverlayPromotionInfo::getPromType).collect(Collectors.toList());
//        for (String promSourceType : promTypeList) {
//            List<String> promTargetTypeList = overlayPromotionRuleMapper.queryPromotionRuleBySourcePromTypeAndRuleResult(promSourceType);
//            if (CollectionUtils.isEmpty(promTargetTypeList)) {
//                continue;
//            }
//
//            for(String promTypeTarget : promTypeList){
//                if(!promSourceType.equals(promTypeTarget)){
//                    promTargetTypeList.contains(promTypeTarget);
//                    return RestResult.error(CouponConstant.Exception.ERROR_CODE,
//                            PromotionTypeEnum.getByCode(Integer.parseInt(promSourceType)).getMessage() + "类型与" + PromotionTypeEnum.getByCode(Integer.parseInt(promTypeTarget)).getMessage() + "类型的活动不能叠加");
//                }
//
//            }

//            boolean flag = promTargetTypeList.contains(promTargetTypeList);
//            if (flag){
//                overlayPromotionRuleMapper.q
//                return RestResult.error(CouponConstant.Exception.ERROR_CODE,
//                        PromotionTypeEnum.getByCode(Integer.parseInt(promSourceType)).getMessage() + "类型与" + PromotionTypeEnum.getByCode(Integer.parseInt(promSourceType)).getMessage() + "类型的活动不能叠加");
//            }

            // 因为两个相同类型的活动互斥比较多，提前判断，减少时间复杂度
//            if (!checkSamePromType(promTargetTypeList, promTypeList, promSourceType)) {
//                return RestResult.error(CouponConstant.Exception.ERROR_CODE,
//                        PromotionTypeEnum.getByCode(Integer.parseInt(promSourceType)).getMessage() + "类型与" + PromotionTypeEnum.getByCode(Integer.parseInt(promSourceType)).getMessage() + "类型的活动不能叠加");
//            }
//
//            String target = promTargetTypeList.stream().filter(targetType -> promTypeList.contains(targetType)).findFirst().orElse(null);
//            if (!StringUtils.isEmpty(target)) {
//                return RestResult.error(CouponConstant.Exception.ERROR_CODE,
//                        PromotionTypeEnum.getByCode(Integer.parseInt(promSourceType)).getMessage() + "类型与" + PromotionTypeEnum.getByCode(Integer.parseInt(target)).getMessage() + "类型的活动不能叠加");
//            }
//        }
//
//        return RestResult.success(true);
//    }


    private boolean checkSamePromType(List<String> promTargetTypeList, List<String> promTypeSourceList, String promSourceType) {
        if (!promTargetTypeList.contains(promSourceType)) {
            return true;
        }
        long promTypeNum = promTypeSourceList.stream().filter(promType -> promType.equals(promSourceType)).count();
        if (promTypeNum > 1) {
            return false;
        }
        return true;
    }

    private Integer getOverlayType(String overlayType) {
        try {
            Integer overlayInt = Integer.parseInt(overlayType);
            return overlayInt;
        } catch (Exception e) {
            return null;
        }
    }

    private String[] getPromotionArray(List<OverlayPromotionInfo> overlayPromotionInfoList) {
        List<String> promotionIdList = overlayPromotionInfoList.stream().map(OverlayPromotionInfo::getPromotionId).collect(Collectors.toList());
        String[] str = promotionIdList.stream().toArray(String[]::new);
        return str;
    }

    public List<List> getGroupList(String[] arr, int start, int[] result, int index, int overlayType, int promotionNum, List<List> groupList) {
        int i = 0;
        for (i = start; i < promotionNum + 1 - index; i++) {
            result[index - 1] = i;
            if (index - 1 == 0) {
                int j;
                List group = new ArrayList(overlayType);
                for (j = overlayType - 1; j >= 0; j--) {
                    group.add(arr[result[j]]);
                }
                groupList.add(group);
            } else {
                getGroupList(arr, i + 1, result, index - 1, overlayType, promotionNum, groupList);
            }
        }
        return groupList;
    }

}